﻿function ServerManager() {
};

ServerManager.prototype.saveInfo = function (score, callback) {
    var self = this;
    var userName = htmlEscape(document.getElementById("txtName").value);

    if (userName == null || userName == "") {
        alert("Enter UserName.");
        return false;
    }

    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("POST", "/Web2048/SaveScore", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("name=" + userName + "&score=" + score);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.Success) {
                alert("저장되었습니다.");
                
                self.getTotalScore();
                callback();

            } else {
                alert("2. 저장에 실패하였습니다.");
            }
        }
    }
};

ServerManager.prototype.getTotalScore = function () {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET", "/Web2048/GetTotalResult", true);
    xmlhttp.send();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var result = JSON.parse(xmlhttp.responseText);

            var html = "";

            result.ScoreList.forEach(function (item, index) {
                html += "<tr><td>" + (index + 1) + "</td>";
                html += "<td>" + item.Name + "</td>";
                html += "<td style='text-align:right' >" + item.Score + "</td>";
                html += "<td>2014/08/01 23:12:58</td></tr>";
            });

            document.getElementById("tbRankingList").innerHTML = html;

        }
    }
};

